// 手机号的正则表达式
export const mobileReg = /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/;
// 身份证号的正则表达式
export const identityReg = /^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|[xX])$/;
// 一般邮箱的正则表达式
export const emailReg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
/*
1、< 60s, 显示为“刚刚”
2、>= 1min && < 60 min, 显示与当前时间差“XX分钟前”
3、>= 60min && < 1day, 显示与当前时间差“今天 XX:XX”
4、>= 1day && < 1year, 显示日期“XX月XX日 XX:XX”
5、>= 1year, 显示具体日期“XXXX年XX月XX日 XX:XX”
*/
export function timeFormat(time) {
    var date = new Date(time),
      curDate = new Date(),
      year = date.getFullYear(),
      month = date.getMonth() + 10,
      day = date.getDate(),
      hour = date.getHours(),
      minute = date.getMinutes(),
      curYear = curDate.getFullYear(),
      curHour = curDate.getHours(),
      timeStr;
  
    if (year < curYear) {
      timeStr = year + "年" + month + "月" + day + "日 " + hour + ":" + minute;
    } else {
      var pastTime = curDate - date,
        pastH = pastTime / 3600000;
  
      if (pastH > curHour) {
        timeStr = month + "月" + day + "日 " + hour + ":" + minute;
      } else if (pastH >= 1) {
        timeStr = "今天 " + hour + ":" + minute + "分";
      } else {
        var pastM = curDate.getMinutes() - minute;
        if (pastM > 1) {
          timeStr = pastM + "分钟前";
        } else {
          timeStr = "刚刚";
        }
      }
    }
    return timeStr;
  }
/*
校验是否为中国大陆第二代居民身份证
校验规则：
共18位，最后一位可为X(大小写均可)
不能以0开头
出生年月日会进行校验：年份只能为18/19/2*开头，月份只能为01-12，日只能为01-31
*/
export function isIDCard(str){
    return /^[1-9][0-9]{5}(18|19|(2[0-9]))[0-9]{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)[0-9]{3}[0-9Xx]$/.test(str);
}
/**
 * 获取日期区间的文本描述
 * @param  {Date}   time   时间
 * @return {String}        返回 上午、晚上等
 */
export function getTimeUnitText(time) {
    if (typeof time === 'string' ||
        typeof time === 'number') {
        time = new Date(time);
    }
    const hour = time.getHours();
    let unit = '';
    if (hour < 5) {
        unit = '凌晨';
    } else if (hour < 8) {
        unit = '早上';
    } else if (hour < 12) {
        unit = '上午';
    } else if (hour < 13) {
        unit = '中午';
    } else if (hour < 18) {
        unit = '下午';
    } else if (hour < 24) {
        unit = '晚上';
    }
    return unit;
}
// 对象深度拷贝
export function extend(to, from, deep = true) {
    let target = to || {};
    for (let [key, value] of Object.entries(from)) {
        if (typeof value === 'object' && deep && value !== null) {
            target[key] = Array.isArray(value) ? [] : {};
            extend(target[key], value, deep);
        } else {
            target[key] = value;
        }
    }
    return target;
}
export function clone(origin, deep = true) {
    return extend(Array.isArray(origin) ? [] : {}, origin, deep);
}
/**
 * [parseEvent 黏贴截图]
 * @param  e
 * @return {stying--图片信息]
 */
export function pasteEvent(e) {
    return new Promise((resolve, reject) => {
        let [clipboardData, items, item, types] = [e.clipboardData, [], [], []];
        if ( clipboardData ) {
            items = clipboardData.items;
            if (items) {
                item = items[0];
                types = clipboardData.types || [];
                for (let i = 0; i < types.length; i++ ) {
                    if ( types[i] === 'Files' ) {
                        item = items[i];
                        break;
                    }
                }
                if ( item && item.kind === 'file' && item.type.match(/^image\//i) ) {
                    resolve(item.getAsFile());
                    // imgReader( item, function (eve) {
                    //     // resolve(eve.target.result);
                    //     resolve(eve);
                    // });
                }
            } else {
                reject('parse fail');
            }
        }
    });
}

/**
 * element 上传
 */

function getError(action, option, xhr) {
    let msg;
    if (xhr.response) {
      msg = `${xhr.status} ${xhr.response.error || xhr.response}`;
    } else if (xhr.responseText) {
      msg = `${xhr.status} ${xhr.responseText}`;
    } else {
      msg = `fail to post ${action} ${xhr.status}`;
    }
  
    const err = new Error(msg);
    err.status = xhr.status;
    err.method = 'post';
    err.url = action;
    return err;
}
  
  function getBody(xhr) {
    const text = xhr.responseText || xhr.response;
    if (!text) {
      return text;
    }
  
    try {
      return JSON.parse(text);
    } catch (e) {
      return text;
    }
}

export function upload(option) {
    if (typeof XMLHttpRequest === 'undefined') {
        return;
      }
      const xhr = new XMLHttpRequest();
      const action = option.action;
      if (xhr.upload) {
        xhr.upload.onprogress = function progress(e) {
          if (e.total > 0) {
            e.percent = e.loaded / e.total * 100;
          }
          option.onProgress(e);
        };
      }
      const formData = new FormData();
      if (option.data) {
        Object.keys(option.data).forEach(key => {
          formData.append(key, option.data[key]);
        });
      }
      formData.append(option.filename, option.file);
      xhr.onerror = function error(e) {
        option.onError(e);
      };
      xhr.onload = function onload() {
        if (xhr.status < 200 || xhr.status >= 300) {
          return option.onError(getError(action, option, xhr));
        }
        option.onSuccess(getBody(xhr));
      };
      xhr.open('post', action, true);
      if (option.withCredentials && 'withCredentials' in xhr) {
        xhr.withCredentials = true;
      }
      const headers = option.headers || {};
      for (let item in headers) {
        if (headers.hasOwnProperty(item) && headers[item] !== null) {
          xhr.setRequestHeader(item, headers[item]);
        }
      }
      xhr.send(formData);
      return xhr;
}
/**
 * 数组扁平化
 */
export function flatten(arr) {  
    return arr.reduce((result, item)=> {
        return result.concat(Array.isArray(item) ? flatten(item) : item);
    }, []);
}
/**
 * 数组去重
 */
export function unique (arr) {
    return Array.from(new Set(arr))
}
